import sys
reload(sys)
sys.setdefaultencoding('utf8')
from PyQt4.QtGui import *
from PyQt4.QtCore import *

from contrib.crawler import *
from contrib.lib import *
from contrib.spider_frontier import *
from contrib.spider_html import *
from contrib.spider_http import *
import configwin
import workwin
class MainWin(QWidget):
    def __init__(self, parent = None):
        QWidget.__init__(self, parent)
        self.config = configwin.ConfigWin()
        self.configLayout = QHBoxLayout()
        self.configLayout.addWidget(self.config)
        self.setLayout(self.configLayout)
        

class App(QApplication):
    def __init__(self,argv):
        QApplication.__init__(self, argv)
        self.configW = configwin.ConfigWin()
        self.configW.show()
        self.setActiveWindow(self.configW)
        self.connect(self.configW, SIGNAL('hided()'), self.showWork)
        self.timer=QTimer()
        self.connect(self.timer,SIGNAL("timeout()"), self.onTimer)
        
    def showWork(self):
        conf = self.configW.getConfig()
        self.link_queue = WorkQueue()
        for url in conf['urls']:
            self.link_queue.add(url)
        
        self.work = workwin.WorkWin()
        self.work.show()
        self.link_queue = WorkQueue()

        self.nest = Nest(conf['projectname'],conf['projectname']+'.db')
        self.nest.initFromSql(conf['sqlfile'])
        self.spider = Crawler(self.nest, self.link_queue)
        #self.nest.start()
        self.timer.start( 1000)
        
    def onTimer(self):
        url = self.link_queue.get()
        self.spider.receive(url) 
        self.spider.run()
        print 'ok'
    
        pass
if __name__ == '__main__':
    import sys
    """
    app = QApplication(sys.argv)
    mw = MainWin()
    mw.show()
    sys.exit(app.exec_())
    """
    app = App(sys.argv)
    sys.exit(app.exec_())